#!/usr/bin/env python2
#-*- coding: utf-8 -*-


import os
import datetime
import xlwt
import MySQLdb
import ConfigParser

from Ump import utils
from Ump.common import exception
from Ump.schedule.jobs.base import JobBase
from Ump.schedule.api import ScheduleApi
from Ump.objs.session_wrapper import _sw
from Ump.schedule.utils import log_info_run
from Ump.objs.db import models
from Ump.common import log
from Ump import defs


job_log = log.get_logger(__name__)


class OplogJob(JobBase):
    def __init__(self):
        config=ConfigParser.RawConfigParser()
        config.read(defs.DB_CFG_PATH)

        if config.has_section('mysql'):
            self.user = config.get('mysql', 'user')
            self.passwd = config.get('mysql', 'password')
            self.db = config.get('mysql', 'database')
            self.host = config.get('mysql', 'host')
            self.port = config.get('mysql', 'port')

    @log_info_run()
    def run(self, context):
        job_log.info('OplogJob! The begin time is: %s' % datetime.datetime.now())

        oplogs = _sw.db_oplog()
        if not oplogs:
            raise exception.OplogNotFound()

        conn=MySQLdb.connect(host="localhost", user=self.user, passwd=self.passwd, db=self.db, charset="utf8")
        cursor = conn.cursor()
 
        count = cursor.execute('select * from oplog')
        cursor.scroll(0, mode='absolute')
        results = cursor.fetchall()
        fields = cursor.description

        wbk = xlwt.Workbook()
        sheet = wbk.add_sheet('oplog', cell_overwrite_ok=True)

        now = datetime.datetime.now()
        path = _sw.get_oplog_export_path(name='oplog_export.path')

        if not os.path.exists(path):
            os.mkdir(path)
        for field in range(0, len(fields)):
            sheet.write(0, field, fields[field][0])

        row = 1
        col = 0
        for row in range(1, len(results)+1):
            for col in range(0, len(fields)):
                sheet.write(row, col, u'%s'%results[row-1][col])

        filename = str(path) + '/' + str(now) + '.xls'
        wbk.save(filename)
        
        job_log.info('OplogJob! The end time is: %s' % datetime.datetime.now())


if __name__ == '__main__':
    op = OplogJob()
    op.run()
